<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <!-- 导入页面的基本样式 -->
    <link rel="stylesheet" href="./css/search.css" />
    <!-- 导入 jQuery -->
    <script src="./lib/jquery.js"></script>
    <script src="./lib/template-web.js"></script>
  </head>
  <body>
    <div class="container">
      <!-- Logo -->
      <img src="./images/taobao_logo.png" alt="" class="logo" />

      <div class="box">
        <!-- tab 栏 -->
        <div class="tabs">
          <div class="tab-active">宝贝</div>
          <div>店铺</div>
        </div>
        <!-- 搜索区域（搜索框和搜索按钮） -->
        <div class="search-box">
          <input
            type="text"
            class="ipt"
            placeholder="请输入要搜索的内容"
          /><button class="btnSearch">搜索</button>
        </div>
        <!-- 搜索建议列表 -->
        <div id="suggest-list"></div>
      </div>
    </div>
    <!-- 模板结构 -->
    <script type="text/html" id="tpl">
      {{each result}}
      <!-- 搜索建议项 -->
      <div class="suggest-item">{{$value[0]}}</div>
      {{/each}}
    </script>

    <script>
      let timer = null;
      // 定义一个全局缓存对象
      let catchObject = {};

      // 定义一个防抖函数
      function fangdou(kw) {
        timer = setTimeout(() => {
          getKeywords(kw);
        }, 500);
      }

      // 给input框绑定keyup事件
      $(".ipt").on("keyup", function () {
        clearTimeout(timer);
        // 去除字符串两端空格
        let keyWords = $(this).val().trim();
        // 判断用户输入的内容是否为空
        if (!keyWords.length) return $("#suggest-list").empty().hide();
        // console.log(keyWords);
        // getKeywords(keyWords);
        if (catchObject[keyWords]) return render(catchObject[keyWords]);
        fangdou(keyWords);
      });

      function getKeywords(kw) {
        // 发起jsonp请求
        $.ajax({
          url: "https://suggest.taobao.com/sug?q=" + kw,
          dataType: "jsonp",
          success: function (res) {
            console.log(res);
            render(res);
          },
        });

        // 渲染页面
        function render(res) {
          if (res.result.length <= 0) {
            return $("#suggest-list").empty().hide();
          }
          const html = template("tpl", res);
          $("#suggest-list").html(html).show();
          let k = $("#ipt").val().trim();
          catchObject[k] = res;
        }
      }
    </script>
  </body>
</html>
